package com.zhugang.week07;

/**
 * @program algorithms
 * @description: constructFromPrePost
 * @author: chanzhugang
 * @create: 2022/07/27 16:37
 */
public class ConstructFromPrePost {

    /**
     * 889 根据前序和后序遍历构造二叉树
     *
     * @param preorder
     * @param postorder
     * @return
     */
    public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
        return myBuildTree(preorder, 0, preorder.length - 1, postorder, 0, postorder.length - 1);
    }

    private TreeNode myBuildTree(int[] pre, int i, int j, int[] post, int p, int r) {
        if (i > j) {
            return null;
        }
        // 前序第一个是根节点
        TreeNode root = new TreeNode(pre[i]);
        if (i == j) {
            return root;
        }
        int q = p;
        // 左子树根节点划分
        while (post[q] != pre[i + 1]) {
            q++;
        }
        // 左子树大小
        int leftTreeSize = q - p + 1;

        TreeNode left = myBuildTree(pre, i + 1, i + leftTreeSize, post, p, q);
        TreeNode right = myBuildTree(pre, i + leftTreeSize + 1, j, post, q + 1, r - 1);
        root.left = left;
        root.right = right;
        return root;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}